package com.example.demo.controller;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.example.demo.constant.SystemConstant;
import com.example.demo.dto.CouponMonitorDTO;
import com.example.demo.mapper.entity.SysUserView;
import com.example.demo.utils.MD5Util;
import com.example.demo.controller.bean.Result;
import com.example.demo.mapper.entity.User;
import com.example.demo.service.UserLoginService;
import com.example.demo.utils.PageBo;
import com.example.demo.utils.PageVo;
import com.example.demo.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Lucy
 * @create 2024-01-28 19:31
 */
@RequestMapping("userLoginController")
@Api("后台管理平台用户登录接口")
@Slf4j
@RestController
public class UserLoginController {
    @Autowired
    private UserLoginService service;

    @Autowired
    private RedisUtil redisUtil;


    @ApiOperation("用户通过用户名密码登录")
    @RequestMapping(value = "passwordLogin", method = {RequestMethod.POST,  RequestMethod.GET} )
    public Result<Object> login(@RequestBody SysUserView loginUser){
        SysUserView currentUser = new SysUserView();
        currentUser.setName(loginUser.getName());
        currentUser = service.selectUserByName(currentUser.getName());
        if (currentUser == null) return Result.fail("账号不存在");
        if (SystemConstant.USER_STATUS_DISABLE == currentUser.getState()) {
            return Result.fail("账号已被禁用，请联系管理员解封");
        }
        int errorNum = 0;
        String key = SystemConstant.userState + ":" + currentUser.getName();
        if (redisUtil.hasKey(key)) {
            errorNum = (int) redisUtil.get(key);
        }
        if (errorNum >= SystemConstant.passwordErrorNum)
            return Result.fail("此账号因密码错误次数太对，已经被暂时禁用。");
        if (!MD5Util.encryptPassword(loginUser.getPassword()).equals(currentUser.getPassword())){
            long time = SystemConstant.passwordErrorNum_Time;
            redisUtil.set(key, errorNum + 1, time);
            return Result.fail("密码错误");
        }
        if (errorNum > 0) redisUtil.del(key);
        // 会话登录，参数填登录人的账号id
        String token = StpUtil.getTokenValue();
        String tokenName = SaManager.getConfig().getTokenName();
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenName", tokenName);
        map.put("username", currentUser.getName());
        map.put("userRole", currentUser.getRoleId());
        if(loginUser.getIsRemeber() == true){
            StpUtil.login(currentUser.getUserId(),true);
        }else{
            StpUtil.login(currentUser.getUserId(),false);
        }
        return Result.ok("登录成功",map);
    }

    @ApiOperation(value = "退出登录", notes = "开发中")
    @RequestMapping(value = "logout", method = {RequestMethod.POST})
    public Result<Object> logout() {
        if (StpUtil.getLoginIdDefaultNull() != null) {
            StpUtil.logout();
            return Result.ok("退出成功");
        } else{
            return Result.warn("未登录");
        }
    }

    @ResponseBody
    @ApiOperation("获取用户数据接口")
    @RequestMapping(value = "getUserInfo", method = {RequestMethod.POST})
    public SaResult getUserInfo() {
        System.out.println("调用获取用户数据接口");
        if (StpUtil.getLoginIdDefaultNull() != null) {
            // 获取当前会话账号id, 如果未登录，则返回 null
            int userId = StpUtil.getLoginIdAsInt();
            SysUserView currentUser = service.getUserInfo(userId);
        //    String avatar = currentUser.getAvatar();
        //    currentUser.setAvatar("https://seedling-classmate.oss-cn-beijing.aliyuncs.com/"+ avatar);
            return SaResult.data(currentUser);
        } else {
            return SaResult.error("未登录");
        }
    }
}
